﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Net.Mime;
using System.Text;
using System.Web;

namespace CYWebService
{
    public class Eamil
    {
        /// <summary>
        /// 发送邮件方法
        /// </summary>
        /// <param name="FromMial">发件人邮箱</param>
        /// <param name="ToMial">收件人邮箱(多个收件人地址用";"号隔开)</param>
        /// <param name="AuthorizationCode">发件人授权码</param>
        /// <param name="ReplyTo">对方回复邮件时默认的接收地址（不设置也是可以的）</param>
        /// <param name="CCMial">//邮件的抄送者(多个抄送人用";"号隔开)</param>
        /// <param name="File_Path">附件的地址</param>
        public bool SendMail(string title, string body, string mail, string fileid, string PicName, string From)//
        {

            string strAccount = "1685575620@qq.com";
            //发送方密码
            string strPwd = "noxmvyovaejwbdej";
            //发送方邮件地址
            string strFrom = "alictex@foxmail.com";
            SmtpClient smtpClient = new SmtpClient("smtp.qq.com", 25);
            smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;//指定电子邮件发送方式
            smtpClient.Credentials = new System.Net.NetworkCredential(strAccount, strPwd);//用户名和密码
            if (mail.Contains(";"))
            {
                mail.Substring(0, mail.Length - 1);
            }
            if (fileid.Contains(";"))
            {
                fileid = fileid.Substring(0, fileid.Length - 1);
            }
            if (PicName.Contains(";"))
            {
                PicName = PicName.Substring(0, PicName.Length - 1);
            }
            List<string> ToMiallist = mail.Split(';').ToList();

            string tomail = "";
            for (int i = 0; i < ToMiallist.Count; i++)
            {
                if (string.IsNullOrEmpty(ToMiallist[i].ToString()))
                {
                    continue;
                }
                if (!string.IsNullOrEmpty(ToMiallist[i].ToString()))
                {
                    tomail = tomail + ToMiallist[i].ToString() + ",";
                }
            }
            tomail=tomail.Substring(0, tomail.Length- 1);
            //MailMessage mailMessage = new MailMessage(strFrom, ToMiallist[i].ToString());
            MailMessage mailMessage = new MailMessage(strFrom, tomail);
            mailMessage.Subject =title;//主题title
           
            mailMessage.Body =body;//内容 body
            if (From == "寄样管理")
            {


                Attachment attachment1 = new System.Net.Mail.Attachment(@"D://Evaluation/images/Alic.png");//http://49.235.71.36/alic/images/Alic.png
                mailMessage.Attachments.Add(attachment1);
                Attachment attachment2 = new System.Net.Mail.Attachment(@"D://Evaluation/images/ViewPic2.png");
                mailMessage.Attachments.Add(attachment2);
                string link = "http://49.235.71.36/alic/SampleList.aspx?obj=5f547baf-9179-49fd-b62c-43e98e1e60c7";
                mailMessage.Body += "<img src=\"cid:" + attachment1.ContentId + "\" style=\"width:90px;height:25px \" />" + "<br><font style='font-size:14px; color:#E2552A'>●</font> info@alic-tex.com <br><font style='font-size:14px; color:#E2552A'>●</font> +86-551-62299551<br><font style='font-size:14px; color:#E2552A'>●</font> Anhui Light Industries International Co., Ltd.<br><font style='font-size:14px; color:#E2552A'>●</font> ALIC Center, 8 Tianda Road, Hefei, Anhui, P.R. China<br><br><font style='font-size:14px; color:#CCC'>Pls don't reply this email which generated by ERP system automaticly .If you have any questions,pls contact with business principal persons directly .<br><br></font>";
                mailMessage.Body += "<a href =" + link + ">" + "<img src=\"cid:" + attachment2.ContentId + "\" style=\"width:180px;height:47px \" />" + " </a>";
            }
            mailMessage.BodyEncoding = System.Text.Encoding.UTF8;//正文编码
            mailMessage.IsBodyHtml = true;//设置为HTML格式
            mailMessage.Priority = MailPriority.High;//优先级
            GetCYData cy = new GetCYData();
            Stream ms;
            if (!string.IsNullOrEmpty(fileid))
            {
                fileid = fileid.Trim();
                List<string> Piclist = fileid.Split(';').ToList();
                List<string> PicNamelist = PicName.Split(';').ToList();
                for (int j = 0; j < Piclist.Count; j++)
                {
                    string contentType = ".png";
                    if (PicName != "" && PicNamelist[j].ToString().Contains("."))
                    {
                        char[] chs = { '.', ';' };
                        contentType = "." + PicNamelist[j].ToString().Trim().Split(chs)[1];
                    }
                    bool flag = File.Exists("C:\\MailPic\\" + Piclist[j].ToString().Trim() + contentType);
                    if (flag == false)
                    {
                        cy.GetFile(Piclist[j].ToString().Trim(), contentType);
                    }
                    string pid = Piclist[j].ToString().Trim();
                    if (flag == true)
                    {
                        Random random = new Random();
                        int randomNumber = random.Next(0, 99);
                        pid = Piclist[j].ToString().Trim() + randomNumber.ToString();
                    }
                    File.Copy(Path.Combine("C:\\MailPic\\" + Piclist[j].ToString().Trim() + contentType), Path.Combine("C:\\MailPic\\", pid+ contentType), true);
                    
                    if (contentType == ".pdf") 
                    {
                        //byte[] bytes = System.Text.Encoding.Default.GetBytes("C:\\MailPic\\" + Piclist[j].ToString().Trim() + contentType);
                        ms = new FileStream("C:\\MailPic\\" + pid + contentType, FileMode.Open);
                        ContentType ct = new ContentType();
                        //附件文件类型
                        ct.MediaType = MediaTypeNames.Application.Pdf;
                        //附件名称，可以是其它后缀名
                        ct.Name = PicNamelist[j].ToString().Trim();
                        mailMessage.Attachments.Add(new Attachment(ms, ct));
                    }
                    else if (contentType == ".xls"|| contentType == ".xlsx")//王艳新加的
                    {
                        //byte[] bytes = System.Text.Encoding.Default.GetBytes("C:\\MailPic\\" + Piclist[j].ToString().Trim() + contentType);
                        ms = new FileStream("C:\\MailPic\\" + pid + contentType, FileMode.Open);
                        ContentType ct1 = new ContentType();
                        //附件文件类型
                        ct1.MediaType = MediaTypeNames.Text.Xml;
                        //附件名称，可以是其它后缀名
                        ct1.Name = PicNamelist[j].ToString().Trim();
                        mailMessage.Attachments.Add(new Attachment(ms, ct1));
                    }
                    else 
                    {
                        if (flag == false)
                        {
                            Attachment attachment = new System.Net.Mail.Attachment("C:\\MailPic\\" + Piclist[j].ToString().Trim() + contentType);
                            mailMessage.Attachments.Add(attachment);
                            mailMessage.Body += "<img src=\"cid:" + attachment.ContentId + "\"/>";
                        }
                        if (flag == true)
                        {
                            Attachment attachment = new System.Net.Mail.Attachment("C:\\MailPic\\" +pid + contentType);
                            mailMessage.Attachments.Add(attachment);
                            mailMessage.Body += "<img src=\"cid:" + attachment.ContentId + "\"/>";
                        }

                    }                
                }

            }
            try
            {
                smtpClient.Send(mailMessage);
                mailMessage.Dispose();//释放资源
                
               
            }
            
            catch (Exception ex)
            {

            }
            //finally
            //{
            //    fileid = fileid.Trim();
            //    List<string> Piclist = fileid.Split(';').ToList();
            //    for (int j = 0; j < Piclist.Count; j++)
            //    {
            //        FileStream ddd = new FileStream("C:\\MailPic\\" + Piclist[j].ToString().Trim() + ".png", FileMode.Open);

            //        if (ddd != null)
            //        {
            //            ddd.Close();
            //        }
            //    }
            //}


            return true;
        }
        public void WriteLog(string text)
        {

            string path = AppDomain.CurrentDomain.BaseDirectory;
            path = System.IO.Path.Combine(path, "Logs\\");

            if (!System.IO.Directory.Exists(path))
            {
                System.IO.Directory.CreateDirectory(path);
            }
            string fileFullName = System.IO.Path.Combine(path
            , string.Format("{0}.txt", DateTime.Now.ToString("yyyyMMdd-HHmm")));


            using (StreamWriter output = System.IO.File.AppendText(fileFullName))
            {
                output.WriteLine(text);
                output.Close();
            }
        }
    }
}